package job.work.config.filter;

import com.alibaba.druid.util.StringUtils;
import job.work.dao.system.dao.DecMenuDao;
import job.work.dao.system.dao.DecRoleMenuDao;
import job.work.domain.course.CommonExcetion;
import job.work.domain.course.TokenIsExpiredException;
import job.work.domain.response.AuthCode;
import job.work.domain.system.entity.pojo.DecMenu;
import job.work.domain.system.entity.pojo.DecRoleMenu;
import job.work.framework.ExceptionCast;
import job.work.utils.Constants;
import job.work.utils.JwtTokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;


/**
 * @author wu on 2020/1/9 0009
 */
@Component
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    Logger logger = LoggerFactory.getLogger(UrlFilterInvocationSecurityMetadataSource.class);

    @Resource
    private HttpServletRequest readHttpServletRequest;

    @Resource
    private DecMenuDao decMenuDao;//菜单接口
   @Resource
    private DecRoleMenuDao decRoleMenuDao;//角色接口

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        String requestUrl = null;


        String requestUrls = ((FilterInvocation) object).getRequestUrl();

        logger.info("请求路径是" + requestUrls);
        if (StringUtils.isEmpty(requestUrls) || "/".equals(requestUrls)) {
            return SecurityConfig.createList();
        }
        String[] split1 = requestUrls.split("\\?");
        for (String s : split1) {
            requestUrl = s;
            logger.info(requestUrl + "截取后的路径是");
            break;
        }
        // 忽略url请放在此处进行过滤放行
        assert requestUrl != null;
        if (requestUrl.contains("/userlogin")|| requestUrl.contains("/login")|| requestUrl.contains("/null")
                || requestUrl.contains("/csrf") || requestUrl.contains("/signInUser")
                || requestUrl.contains("/smscodecode")  || requestUrl.contains("/userloginMobile")
                || requestUrl.contains("/userlogout") || requestUrl.contains("/error")) {
            return SecurityConfig.createList();

        }
        String token ="";

        try {
            String token1 = readHttpServletRequest.getHeader("token");
            if (StringUtils.isEmpty(token1)) {
                return SecurityConfig.createList();
            }
            token = token1.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        } catch (CommonExcetion e) {

          ExceptionCast.cast(AuthCode.AUTH_LOGIN_TOKEN_ILLEGAL);

        }
        if (StringUtils.isEmpty(token)) {
            return SecurityConfig.createList();
        }

     //   return SecurityConfig.createList();

        String userRole = null;
        try {
            userRole = JwtTokenUtils.getUserRole(token);
            if (userRole == null){
                throw new TokenIsExpiredException("token超时了");
            }
        } catch (IllegalArgumentException | TokenIsExpiredException e) {
            e.printStackTrace();
           // ExceptionCast.cast(AuthCode.AUTH_LOGIN_TOKEN_TIME);

        }

        //这个是菜单
        DecMenu byUrl = decMenuDao.findByUrl(requestUrl);
        if (byUrl == null){
            return SecurityConfig.createList();
        }
        //因为是菜单Id所以用这个方法根据菜单ID查询那些角色对应这个菜单
        List<DecRoleMenu> byRoleId = decRoleMenuDao.findByMenuId(byUrl.getId());

        for (DecRoleMenu decRoleMenu : byRoleId) {
            Long roleId = Long.valueOf(userRole);
            if (decRoleMenu.getRoleId().equals(roleId)){
                return SecurityConfig.createList();
            }
        }
        return SecurityConfig.createList(Constants.ROLE_LOGIN);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }

}
